# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class ScrapyProjectPipeline:
    def open_spider(self, spider):
        self.client = pymongo.MongoClient("mongodb://localhost:27017")
        self.db = self.client.get_database('lianxi')
        self.collection = self.db.get_collection('lianxi')


        self.items = []
    def process_item(self, item, spider):
        if spider.name == "lianxi":

            self.items.append(item)
            if len(self.items) >= 15:
                self.collection.insert_many(self.items)
                self.items.clear()


    def close_spider(self, spider):
        if self.items:
            self.collection.insert_many(self.items)
            self.items.clear()
        self.client.close()